<?php
namespace app\manage\controller;
use think\Db;
use think\Log;

class System extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }


    public function index()
    {
        // 查询条件start
        $uid = input('uid');
        $start_time = input('start_time');
        $end_time = input('end_time');
        $map = [];
        if($uid != null){
            $map['uid'] = $uid;
        }
        if($start_time != null && $end_time != null){
            $start = strtotime($start_time);
            $end = strtotime($end_time);
            if($end > $start) $map['create_time'] = ['between',[$start,$end]];
        }
        // 查询条件end

        $systemLogs = model('SystemLog')->getInfosByMap($map, '', false);
        $count = model('SystemLog')->countNum($map,false);
        return $this->fetch('', [
            'systemLogs' => $systemLogs,
            'count' => $count,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'uid' => $uid
        ]);
    }

    public function log()
    {
        // 查询条件start
        $clue_id = input('clue_id');
        $start_time = input('start_time');
        $end_time = input('end_time');
        $pro_id = input('pro_id','');
        $title = input('title','');

        $map = [];
        if($clue_id != null){
            $map['a.clue_id'] = $clue_id;
        }
        if($start_time != null && $end_time != null){
            $start = strtotime($start_time);
            $end = strtotime($end_time);
            if($end > $start) $map['a.create_time'] = ['between',[$start,$end]];
        }elseif ($start_time != null && empty($end_time) ){
            $start = strtotime($start_time);
            $map['a.create_time'] = ['>=',$start];
        }elseif ( empty($start_time) && $end_time != null ){
            $end = strtotime($end_time);
            $map['a.create_time'] = ['<=',$end];
        }

        if($pro_id!=''){
            $map['b.pro_id']=$pro_id;
        }
        if($title!=''){
            $map['a.title']=['like','%'.$title.'%'];
        }

        // 查询条件end

//        $systemLogs = model('ClueErrorLog')->getInfosByMap($map, '', false);

        $systemLogs = model('ClueErrorLog')->alias('a')->field('a.*,b.clue_name,b.phone,b.city,b.adv_id,c.acc_name,c.acc_desc,b.pro_id')
            ->join('clue b','a.clue_id=b.clue_id','LEFT')
            ->join('account c','c.adv_id=b.adv_id','LEFT')
            ->where($map)
            ->order('a.id desc')->paginate();

        $productAll =Db::name('product')->column('name','id');

//        dump($systemLogs);die;

        foreach ($systemLogs as &$v){
            $v['product_name']=empty($v['pro_id'])?'未知':$productAll[$v['pro_id']];
            $cityText='';
            if(!empty($v['city'])){
                $ids = explode('-',$v['city']);
                $prov = $this->getCityName($ids[0]);
                if(!empty($ids[1])){
                    $city = $this->getCityName($ids[1]);
                }else{
                    $city=$prov;
                }
                if($prov == $city){
                    $cityText = $prov;
                }else{
                    $cityText = $prov.'-'.$city;
                }
            }
            $v['city']=$cityText;
        }
        $products = model('Product')->where('status',1)->column('name','id');
        return $this->fetch('', [
            'systemLogs' => $systemLogs,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'clue_id' => $clue_id,
            'pro_id' => $pro_id,
            'products' => $products,
            'title' => $title,
        ]);
    }

    public function edit()
    {
        $id = input('id');
        if(!$id) return self::showReturnCode(1002,'id 错误');
        $info = model('ClueErrorLog')->getInfoByMap(['id'=>$id]);
        return self::showJsonReturnCodeData('1001',$info,'');
    }

    public function error_log()
    {
		$time = input('time');
        if(!$time){
            $time = date('Y-m-d',time());
            $time_str = date('Ym',time()).'/'.date('d',time());
        }else{
            $time_str = date('Ym',strtotime($time)).'/'.date('d',strtotime($time));
        }
        $infos = [];
       $filename = "/home/wwwroot/cld/log/".$time_str.'.log';
//       $filename = "D:\phpstudy_pro\WWW\cld\log/".$time_str.'.log';
        if(is_file($filename)){
            $handle = fopen($filename, "r");//读取二进制文件时，需要将第二个参数设置成'rb'

            //通过filesize获得文件大小，将整个文件一下子读到一个字符串中
            $contents = fread($handle, filesize ($filename));
            fclose($handle);
            $arr = explode('---------------------------------------------------------------',$contents);

            $infos = array_reverse($arr);

            foreach ($infos as $k=>$v){
                //$infos[$k] = str_replace("[ error ]","<br/>[ error ]",$v);
                $infos[$k] = str_replace(array("[ info ]","[ error ]"),array("<br/>[ info ]","<br/>[ error ]"),$v);
            }
        }


        return $this->fetch('',['infos'=>$infos,'time'=>$time]);
    }

    //线索请求记录
    public function clue_api_log(){
        // 查询条件start
        $adv_id = input('adv_id');
        $clue_name = input('clue_name','');
        $phone = input('phone','');
        $city = input('city','');
        $status = input('status','');
        $start_time = input('start_time');
        $end_time = input('end_time');
        $map = [];
        if($adv_id != null){
            $map['a.adv_id'] = $adv_id;
        }

        if($clue_name != ''){
            $map['a.name'] = ['like','%'.$clue_name.'%'];
        }
        if($phone != ''){
            $map['a.phone'] = $phone;
        }
        if($city != ''){
            $map['a.city'] = ['like','%'.$city.'%'];
        }
        if($start_time != null && $end_time != null){
            $start = $start_time;
            $end = $end_time;
            if($end > $start) $map['a.create_time'] = ['between',[$start,$end]];
        }elseif ($start_time != null && empty($end_time) ){
            $start = $start_time;
            $map['a.create_time'] = ['>=',$start];
        }elseif ( empty($start_time) && $end_time != null ){
            $end = $end_time;
            $map['a.create_time'] = ['<=',$end];
        }

        if($status!=''){
            $map['a.status'] = $status;
        }

        // 查询条件end

        $systemLogs =model('ClueApiLog')->alias('a')->field('a.*,b.acc_name,b.acc_desc')
            ->join('account b','b.adv_id=a.adv_id','LEFT')
            ->where($map)->order('a.id desc')->paginate(20);
//        foreach ($systemLogs as &$v){
////            dump(json_decode($v['data'],true));
////            $systemLogs[$k]['param']=json_decode($v['param'],true);
////            $systemLogs[$k]['data']=json_decode($v['data'],true);
//        }

//        dump($systemLogs);die;

        return $this->fetch('', [
            'systemLogs' => $systemLogs,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'clue_name' => $clue_name,
            'phone' => $phone,
            'city' => $city,
            'adv_id' => $adv_id,
            'status' => $status
        ]);
    }

    public function dbDel(){

        $systemLogs =Db::name('system_del_db')->order('sort desc')->select();

        return $this->fetch('', [
            'systemLogs' => $systemLogs,
        ]);
    }

    public function tableSave(){

        if(request()->isAjax()){
            try{

                $id = input('post.id');
                $save_data = input('post.');

                if(empty($save_data['name'])){
                    return self::showReturnCode(1011,'名称不能为空');
                }

                if(empty($save_data['table_name'])){
                    return self::showReturnCode(1011,'表名不能为空');
                }

                if(empty($save_data['sort'])){
                    $save_data['sort']=0;
                }

                $result = Db::name('system_del_db')->insert($save_data);
                if($result){
                    $this->RecordSystemLog($this->uid,$this->behavior,'保存成功');
                    return self::showReturnCode(1001,'保存成功');
                }else{
                    return self::showReturnCode(1011,'保存失败');
                }
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,'保存失败');
            }
        }else{
            return self::showReturnCode(1002);
        }

    }
    //删除表
    public function tableDel(){

        if($this->request->isAjax()){
            $id = input('post.id');
            $res = Db::name('system_del_db')->delete($id);


            if($res){
                $this->RecordSystemLog($this->uid,$this->behavior,'删除成功,操作ID: '.$id);
                return $this->showReturnCode(1001,'删除成功');
            }else{
                return $this->showReturnCode(1009,'删除失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }

    }

    //删除数据
    public function dbDelete(){
        //2024-05-15 22:47:00 - 2024-05-15 23:00:00
        $id = input('post.id/a');
        $times = input('post.times');
        if(empty($times)){
            return self::showReturnCode(1011,'时间不能为空');
        }else{
            $timeArr=explode(' - ',$times);
            $map1['create_time'] = ['between',[strtotime($timeArr[0]),strtotime($timeArr[1])]];
            $map2['create_time'] = ['between',[$timeArr[0],$timeArr[1]]];
            $map3['time'] = ['between',[$timeArr[0],$timeArr[1]]];
        }

        $bool=$this->tokenBucket($this->uid,'dbDelete',10,1);
        if(!$bool){
            return $this->showReturnCode(1009,'请勿频繁操作');
        }

        \db()->startTrans();
        try {
            $list=Db::name('system_del_db')->field('table_name,name,time_type')->whereIn('id',$id)->select();

            $DbConfig=config('database')['backup_dbhost'];
            foreach ($list as $v){
                $tableName=$v['table_name'];
                if($v['time_type']==1){

                    if ($tableName == 'clue') {
                        $clue_field = Db::name($tableName)->getTableFields();
                        $clue_backup_field = Db::connect($DbConfig)->name('wy_' . $tableName)->getTableFields();
                        $insert_clue_field = array_intersect($clue_field, $clue_backup_field);

                        $clue_log_field = Db::name('clue_log')->getTableFields();
                        $clue_log_bk_field = Db::connect($DbConfig)->name('wy_clue_log')->getTableFields();
                        $insert_clue_log_field = array_intersect($clue_log_field, $clue_log_bk_field);

                        $clue_log_sub_mer_field = Db::name('clue_log_sub_mer')->getTableFields();
                        $clue_log_sub_mer_bk_field = Db::connect($DbConfig)->name('wy_clue_log_sub_mer')->getTableFields();
                        $insert_clue_log_sub_mer_field = array_intersect($clue_log_sub_mer_field, $clue_log_sub_mer_bk_field);

                        $clue_progress_field = Db::name('clue_progress')->getTableFields();
                        $clue_progress_bk_field = Db::connect($DbConfig)->name('wy_clue_progress')->getTableFields();
                        $insert_clue_progress_field = array_intersect($clue_progress_field, $clue_progress_bk_field);

                        $clue_progress_not_push_field = Db::name('clue_progress_not_push')->getTableFields();
                        $clue_progress_not_push_bk_field = Db::connect($DbConfig)->name('wy_clue_progress_not_push')->getTableFields();
                        $insert_clue_progress_not_push_field = array_intersect($clue_progress_not_push_field, $clue_progress_not_push_bk_field);

                        $delData = Db::name($tableName)->field($insert_clue_field)->where($map1)->chunk(300, function ($dbData) use ($DbConfig, $tableName,
                            $insert_clue_log_field, $insert_clue_log_sub_mer_field, $insert_clue_progress_field, $insert_clue_progress_not_push_field) {
                            $res = Db::connect($DbConfig)->name('wy_' . $tableName)->insertAll($dbData);
                            $clueIdArr = array_column($dbData, 'id');
                            $clueLog = Db::name('clue_log')->field($insert_clue_log_field)->whereIn('clue_id', $clueIdArr)->select();
                            $clueLog2 = Db::name('clue_log_sub_mer')->field($insert_clue_log_sub_mer_field)->whereIn('clue_id', $clueIdArr)->select();
                            $clueP = Db::name('clue_progress')->field($insert_clue_progress_field)->whereIn('clue_id', $clueIdArr)->select();
                            $clueP2 = Db::name('clue_progress_not_push')->field($insert_clue_progress_not_push_field)->whereIn('clue_id', $clueIdArr)->select();

                            if ($clueLog) {
                                $res = Db::connect($DbConfig)->name('wy_clue_log')->insertAll($clueLog);
                                Db::name('clue_log')->whereIn('clue_id', $clueIdArr)->delete();
                            }
                            if ($clueLog2) {
                                $res = Db::connect($DbConfig)->name('wy_clue_log_sub_mer')->insertAll($clueLog2);
                                Db::name('clue_log_sub_mer')->whereIn('clue_id', $clueIdArr)->delete();
                            }
                            if ($clueP) {
                                $res = Db::connect($DbConfig)->name('wy_clue_progress')->insertAll($clueP);
                                Db::name('clue_progress')->whereIn('clue_id', $clueIdArr)->delete();
                            }
                            if ($clueP2) {
                                $res = Db::connect($DbConfig)->name('wy_clue_progress_not_push')->insertAll($clueP2);
                                Db::name('clue_progress_not_push')->whereIn('clue_id', $clueIdArr)->delete();
                            }

                        });
                        Db::name($tableName)->where($map1)->delete();
                    } elseif ($tableName == 'clue_cost_log') {
                        $table_field = Db::name($tableName)->getTableFields();
                        $table_backup_field = Db::connect($DbConfig)->name('wy_' . $tableName)->getTableFields();
                        $insert_field = array_intersect($table_field, $table_backup_field);

                        $delData = Db::name($tableName)->field($insert_field)->where($map3)->chunk(300, function ($dbData) use ($DbConfig, $tableName) {
                            $res = Db::connect($DbConfig)->name('wy_' . $tableName)->insertAll($dbData);
                        });
                        Db::name($tableName)->where($map3)->delete();
                    } else {
                        $table_field = Db::name($tableName)->getTableFields();
                        $table_backup_field = Db::connect($DbConfig)->name('wy_' . $tableName)->getTableFields();
                        $insert_field = array_intersect($table_field, $table_backup_field);

                        $delData = Db::name($tableName)->field($insert_field)->where($map1)->chunk(300, function ($dbData) use ($DbConfig, $tableName) {
                            $res = Db::connect($DbConfig)->name('wy_' . $tableName)->insertAll($dbData);
                        });
                        Db::name($tableName)->where($map1)->delete();
                    }


                } else {
                    $table_field = Db::name($tableName)->getTableFields();
                    $table_backup_field = Db::connect($DbConfig)->name('wy_' . $tableName)->getTableFields();
                    $insert_field = array_intersect($table_field, $table_backup_field);

                    $delData = Db::name($tableName)->field($insert_field)->where($map2)->chunk(300, function ($dbData) use ($DbConfig, $tableName) {
                        $res = Db::connect($DbConfig)->name('wy_' . $tableName)->insertAll($dbData);
                    });
                    Db::name($tableName)->where($map2)->delete();
                }
            }
            \db()->commit();
        } catch (\Exception $e) {
            \db()->rollback();
            $errData=[
                'code'=>$e->getCode(),
                'msg'=>$e->getMessage(),
                'flie'=>$e->getFile(),
                'line'=>$e->getLine(),
            ];
            trace($errData,'error');
            return $this->showReturnCode(1009,'删除失败');
        }

        trace('管理员'.$this->uid.":删除".$times.json_encode($list,JSON_UNESCAPED_UNICODE),'error');
        return $this->showReturnCode(1001,'删除成功');
    }

    public function clearCity(){


        $bool=$this->tokenBucket($this->uid,'dbDeleteCity',10,1);
        if(!$bool){
            return $this->showReturnCode(1009,'请勿频繁操作');
        }

        $dataList=Db::name('city')->field('id,remark')->where('remark','<>','')->select();

        $DbConfig=config('database')['backup_dbhost'];
        foreach ($dataList as $v){
            $tableName='city';
            $res=Db::connect($DbConfig)->name('wy_'.$tableName)->where('id',$v['id'])->update(['remark'=>$v['remark']]);
        }
        if(!empty($dataList)){
            Db::name($tableName)->whereIn('id',array_column($dataList,'id'))->update(['remark'=>'']);
        }
        trace('管理员'.$this->uid.":清除城市备注".json_encode($dataList,JSON_UNESCAPED_UNICODE),'error');
        return $this->showReturnCode(1001,'清除成功');
    }


    public function clueErrLog()
    {
        // 查询条件start
        $id = input('id');
        $adv_id = input('adv_id');
        $start_time = input('start_time');
        $end_time = input('end_time');
        $map = [];
        if($id != null){
            $map['clue_id'] = $id;
        }

        if($adv_id != null){
            $map['adv_id'] = $adv_id;
        }
        if($start_time != null && $end_time != null){
            $start = strtotime($start_time);
            $end = strtotime($end_time);
            if($end > $start) $map['create_time'] = ['between',[$start,$end]];
        }

        $productAll =Db::name('product')->column('name','id');

        // 查询条件end

        $systemLogs = model('ClueErrLog')->getInfosByMap($map, '', false);
        $count = model('ClueErrLog')->countNum($map,false);

        foreach ($systemLogs as &$v){

            $v['type_name']=config('clue.err_log_type')[$v['type']];
            $v['pro_name']=empty($v['pro_id'])?'未知':$productAll[$v['pro_id']];

            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $v['city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $v['city'] = $prov;
                    }else{
                        $v['city'] = $prov.'-'.$city;
                    }
                }
            }

        }


        return $this->fetch('', [
            'systemLogs' => $systemLogs,
            'count' => $count,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'id' => $id,
            'adv_id' => $adv_id
        ]);
    }

    public function clueErrPushLog()
    {
        // 查询条件start
        $id = input('id');
        $adv_id = input('adv_id');
        $start_time = input('start_time');
        $end_time = input('end_time');
        $map = [];
        if($id != null){
            $map['a.clue_id'] = $id;
        }

        if($adv_id != null){
            $map['a.push_id'] = $adv_id;
        }
        if($start_time != null && $end_time != null){
            $start = strtotime($start_time);
            $end = strtotime($end_time);
            if($end > $start) $map['a.create_time'] = ['between',[$start,$end]];
        }

        $productAll =Db::name('product')->column('name','id');

        // 查询条件end

        $systemLogs = model('clueErrPushLog')->alias('a')->field('a.*,b.mer_name')
            ->join('merchant b','b.id=a.mer_id')
            ->where($map)
            ->order('a.id desc')
            ->paginate();
//            ->getInfosByMap($map, '', false);
        $count = model('clueErrPushLog')->alias('a')->join('merchant b','b.id=a.mer_id')
            ->where($map)->count();

        foreach ($systemLogs as &$v){

            $v['pro_name']=empty($v['pro_id'])?'未知':$productAll[$v['pro_id']];

            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $v['city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $v['city'] = $prov;
                    }else{
                        $v['city'] = $prov.'-'.$city;
                    }
                }
            }

        }

        return $this->fetch('', [
            'systemLogs' => $systemLogs,
            'count' => $count,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'id' => $id,
            'adv_id' => $adv_id
        ]);
    }

}